/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package mbos.controller;

import java.io.IOException;
import java.io.Serializable;
import java.util.List;
import mbos.entities.Account;
import mbos.entities.enums.AccountType;
import mbos.facade.AccountFacade;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;

/**
 *
 * @author mier
 */
@ManagedBean
@SessionScoped
public class AccountController implements Serializable {

    @EJB
    private AccountFacade accountFacade;
    private Account current = new Account();

    public Account getCurrent() {
        return current;
    }

    public void create() {
        System.out.println(current);
        current.setEmpStat(0);
        current.setConStat(0);
        current.setAcctType(AccountType.WAITER);
        accountFacade.create(current);
    }

    public void login() throws IOException {
        FacesContext fc = FacesContext.getCurrentInstance();
        List<Account> accounts = accountFacade.login(current);

        FacesMessage messageErr =
                new FacesMessage(FacesMessage.SEVERITY_ERROR,
                "Sorry, wrong username or password",
                "No user found !");

        FacesMessage messageSucc =
                new FacesMessage(FacesMessage.SEVERITY_ERROR,
                "Successfully Login",
                "User found !");

        if (accounts.size() > 0) {
            fc.getExternalContext().getSessionMap().put("LOGIN", "LOGIN_SUCCESS");
            fc.addMessage("messages", messageSucc);
            if (accounts.get(0).getAcctType().equals(AccountType.ADMIN)) {
                fc.getExternalContext().getSessionMap().put("ACCOUNT_TYPE", AccountType.ADMIN);
            }else if(accounts.get(0).getAcctType().equals(AccountType.CASHIER)){
                fc.getExternalContext().getSessionMap().put("ACCOUNT_TYPE", AccountType.CASHIER);
            }
            fc.getExternalContext().redirect("/mbos/app/");
        } else {
            fc.addMessage("messages", messageErr);
        }
    }
}
